//
//  NSArray+TZExtension.m
//  TZOCExtension
//
//  Created by Tim.Z on 2017/1/16.
//  Copyright © 2017年 Tim.Z. All rights reserved.
//

#import "NSArray+TZExtension.h"

@implementation NSArray (TZExtension)

- (id)tz_randomObject {
    if (self.count) {
        return self[arc4random_uniform((u_int32_t)self.count)];
    }
    return nil;
}

- (id)tz_objectOrNilAtIndex:(NSUInteger)index{
    return index < self.count ? self[index] : nil;
}

- (NSString *)tz_jsonStringEncoded {
    if ([NSJSONSerialization isValidJSONObject:self]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:0 error:&error];
        NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return json;
    }
    return nil;
}

- (NSString *)tz_jsonPrettyStringEncoded {
    if ([NSJSONSerialization isValidJSONObject:self]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return json;
    }
    return nil;
}

@end
